//
//  TicketListViewController.m
//  WeiShangKeProj
//
//  Created by 焱 孙 on 15/5/28.
//  Copyright (c) 2015年 visionet. All rights reserved.
//

#import "TicketListViewController.h"
#import "Utils.h"
#import "TicketVo.h"
#import "TicketListCell.h"
#import "TicketDetailViewController.h"
#import "UIViewExt.h"
#import "ExtScope.h"

@interface TicketListViewController ()

@end

@implementation TicketListViewController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"UpdateTicketList" object:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self initView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (self.ticketListType == TicketListAllType)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:kDrawerAddPanGesture object:nil];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if (self.ticketListType == TicketListAllType)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:kDrawerRemovePanGesture object:nil];
    }
    [self.userSearchDisplayController setActive:NO animated:YES];
}

-(void)initView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (self.ticketListType == TicketListAllType)
    {
        //左边按钮
        UIButton *btnBack = [Utils buttonWithImageName:[UIImage imageNamed:@"nav_setting"] frame:[Utils getNavLeftBtnFrame:CGSizeMake(100,76)] target:self action:nil];
        [btnBack addTarget:self action:@selector(showSideMenu) forControlEvents:UIControlEventTouchUpInside];
        [self setLeftBarButton:btnBack];
        //notice num view
        NoticeNumView *noticeNumView = [[NoticeNumView alloc]initWithFrame:CGRectMake(25.5, 6+kStatusBarHeight, 18, 18)];
        [self.view addSubview:noticeNumView];
    }
    else
    {
        //右边按钮
        UIButton *addTeamItem = [Utils buttonWithImageName:[UIImage imageNamed:@"nav_add_menu"] frame:[Utils getNavRightBtnFrame:CGSizeMake(100,76)] target:self action:@selector(addTicket)];
        [self setRightBarButton:addTeamItem];
    }
    
    [self setTopNavBarTitle:@"列表"];
    
    //搜索框
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    self.searchBar.placeholder = [Common localStr:@"Common_SearchTitle" value:@"搜索"];
    self.searchBar.delegate = self;
    self.searchBar.frame = CGRectMake(0, NAV_BAR_HEIGHT, kScreenWidth, 44);
    [self.view addSubview:self.searchBar];
    
    self.userSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
    self.userSearchDisplayController.searchResultsDataSource = self;
    self.userSearchDisplayController.searchResultsDelegate = self;
    self.userSearchDisplayController.delegate = self;
    self.userSearchDisplayController.searchResultsTableView.showsVerticalScrollIndicator = NO;
    
    //2.全部用户
    self.tableViewTicketList = [[PullingRefreshTableView alloc]initWithFrame:CGRectMake(0, NAV_BAR_HEIGHT+44, kScreenWidth, kScreenHeight-NAV_BAR_HEIGHT-44) pullingDelegate:self];
    self.tableViewTicketList.dataSource = self;
    self.tableViewTicketList.delegate = self;
    self.tableViewTicketList.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableViewTicketList];
    
    if (self.ticketListType == TicketListCustomerType)
    {
        self.tableViewTicketList.headerOnly = YES;
        self.tableViewTicketList.footerOnly = YES;
        
        self.searchBar.hidden = YES;
        self.tableViewTicketList.frame = CGRectMake(0, NAV_BAR_HEIGHT, kScreenWidth, kScreenHeight-NAV_BAR_HEIGHT);
    }
 
    //no search view
    self.noSearchView = [[NoSearchView alloc]initWithFrame:CGRectMake(0, self.tableViewTicketList.top, kScreenWidth, self.tableViewTicketList.height) andDes:nil];
 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateList) name:@"UpdateTicketList" object:nil];
}

-(void)initData
{
    self.aryTicketList = [NSMutableArray array];
    self.aryFilteredObject = [NSMutableArray array];
    
    self.nCurrPage = 1;
    self.strSearchText = @"";
    [self loadData];
}

-(void)updateList
{
    self.nCurrPage = 1;
    self.refreshing = YES;
    [self loadData];
}

- (void)loadData
{
    //block
    void (^resultBlock)(ServerReturnInfo *retInfo) = ^(ServerReturnInfo *retInfo) {
        if (retInfo.bSuccess)
        {
            NSMutableArray *dataArray = retInfo.data;
            if (self.refreshing)
            {
                if (dataArray != nil)
                {
                    //下拉刷新
                    [self.aryTicketList removeAllObjects];
                    [self.aryTicketList addObjectsFromArray:dataArray];
                }
            }
            else
            {
                //上拖加载
                [self.aryTicketList addObjectsFromArray:dataArray];
            }
            
            [self.tableViewTicketList tableViewDidFinishedLoading];
            if (dataArray != nil && dataArray.count>0)
            {
                self.nCurrPage ++;
            }
            
            NSNumber *numberTotal = retInfo.data2;
            if (numberTotal != nil && numberTotal.integerValue<=self.aryTicketList.count)
            {
                //已经加载完毕
                self.tableViewTicketList.reachedTheEnd = YES;
            }
            else
            {
                //没有全部加载完毕
                self.tableViewTicketList.reachedTheEnd = NO;
            }
            
            [self.tableViewTicketList reloadData];
            
            if (self.aryTicketList.count == 0)
            {
                [self.view addSubview:self.noSearchView];
                self.tableViewTicketList.headerOnly = YES;
            }
            else
            {
                [self.noSearchView removeFromSuperview];
                self.tableViewTicketList.headerOnly = NO;
            }
        }
        else
        {
            [self.tableViewTicketList tableViewDidFinishedLoading];
            [Common tipAlert:retInfo.strErrorMsg];
        }
    };
    
    //Request action
    if (self.aryTicketList.count > 0)
    {
        if (self.refreshing)
        {
            //下拉刷新
            self.nCurrPage = 1;
        }
        else
        {
            //上拖加载
        }
    }
    if (self.ticketListType == TicketListCustomerType)
    {
        [ServerProvider getTicketList:nil page:self.nCurrPage pageSize:10000 status:0 custId:self.m_chatObjectVo.strCustomerID result:resultBlock];
    }
    else
    {
        //关注的人分享列表
        [ServerProvider getTicketList:nil page:self.nCurrPage pageSize:10 status:0 custId:nil result:resultBlock];
    }
    
}

- (void)showSideMenu
{
    [[NSNotificationCenter defaultCenter]postNotificationName:kDrawerOpenLeftSide object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)doSearch
{
    //1.Condition Check
    if (self.strSearchText == nil || self.strSearchText.length<=0)
    {
        return;
    }
    
    //暂时只能搜索前30条记录
    [self isHideActivity:NO];
    [ServerProvider getTicketList:self.strSearchText page:1 pageSize:30  status:0 custId:nil result:^(ServerReturnInfo *retInfo) {
        [self isHideActivity:YES];
        if (retInfo.bSuccess)
        {
            NSMutableArray *aryTemp = (NSMutableArray *)retInfo.data;
            dispatch_async(dispatch_get_main_queue(),^{
                [self.aryFilteredObject removeAllObjects];
                if (aryTemp != nil && [aryTemp count] > 0)
                {
                    [self.aryFilteredObject addObjectsFromArray:aryTemp];
                    [self.searchDisplayController.searchResultsTableView reloadData];
                    [self.searchDisplayController.searchResultsTableView scrollsToTop];
                }
                else
                {
                    [self.searchDisplayController.searchResultsTableView reloadData];
                }
                [self isHideActivity:YES];
            });
        }
        else
        {
            
        }
    }];
}

//增加工单
- (void)addTicket
{
//    TicketDetailViewController *ticketDetailViewController = [[TicketDetailViewController alloc]init];
//    ticketDetailViewController.ticketDetailType = TicketDetailAddType;
//    TicketVo *ticketVo = [[TicketVo alloc]init];
//    ticketVo.strSessionID = self.m_chatObjectVo.strID;
//    ticketDetailViewController.m_ticketVo = ticketVo;
//    ticketDetailViewController.aryOutTicket = self.aryTicketList;
//    ticketDetailViewController.refreshTicketBlock = ^(){[self updateList];};
//    [self.navigationController pushViewController:ticketDetailViewController animated:YES];
}

#pragma mark Table View
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableViewTicketList)
    {
        //客户列表
        return  [self.aryTicketList count];
    }
    else
    {
        //搜索结果
        if(self.aryFilteredObject.count > 0)
        {
            return self.aryFilteredObject.count;
        }
        else
        {
            return 0;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableViewTicketList)
    {
        //列表
        TicketVo *ticketVo = self.aryTicketList[indexPath.row];
        static NSString *identifier=@"TicketListCell";
        TicketListCell *cell = (TicketListCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil)
        {
            cell = [[TicketListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
            
            //改变选中背景色
            UIView *viewSelected = [[UIView alloc] initWithFrame:cell.frame];
            viewSelected.backgroundColor =TABLEVIEW_SELECTED_COLOR;
            cell.selectedBackgroundView = viewSelected;
        }
        [cell initWithData:ticketVo];
        return  cell;
    }
    else
    {
        //搜索结果
        TicketVo *ticketVo = nil;
        if (self.aryFilteredObject.count == 0)
        {
            
        }
        else
        {
            ticketVo = self.aryFilteredObject[indexPath.row];
        }
        static NSString *identifier=@"SearchListCell";
        TicketListCell *cell = (TicketListCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil)
        {
            cell = [[TicketListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
            
            //改变选中背景色
            UIView *viewSelected = [[UIView alloc] initWithFrame:cell.frame];
            viewSelected.backgroundColor =TABLEVIEW_SELECTED_COLOR;
            cell.selectedBackgroundView = viewSelected;
        }
        [cell initWithData:ticketVo];
        return  cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TicketVo *ticketVo;
    if (tableView == self.tableViewTicketList)
    {
        //客户列表
        ticketVo = self.aryTicketList[indexPath.row];
    }
    else
    {
        //搜索结果
        if (self.aryFilteredObject.count == 0)
        {
            return;
        }
        
        ticketVo = self.aryFilteredObject[indexPath.row];
    }
    
    TicketDetailViewController *ticketDetailViewController = [[TicketDetailViewController alloc]init];
    ticketDetailViewController.m_ticketVo = ticketVo;
    if (self.ticketListType == TicketListCustomerType)
    {
        //ticketDetailViewController.aryOutTicket = self.aryTicketList;
    }
    
    @weakify(self)
    ticketDetailViewController.refreshTicketBlock = ^(){
        @strongify(self)
        [self updateList];
    };
    ticketDetailViewController.ticketDetailType = TicketDetailModifyType;
    [self.navigationController pushViewController:ticketDetailViewController animated:YES];
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView
{
    self.refreshing = YES;
    [self loadData];
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView
{
    self.refreshing = NO;
    [self loadData];
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableViewTicketList)
    {
        [self.tableViewTicketList tableViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView == self.tableViewTicketList)
    {
        [self.tableViewTicketList tableViewDidEndDragging:scrollView];
    }
}

#pragma mark - UISearchBarDelegate
- (void)scrollTableViewToSearchBarAnimated:(BOOL)animated
{
    [self.tableViewTicketList scrollRectToVisible:self.searchBar.frame animated:animated];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //文字改变
    self.strSearchText = searchText;
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    //恢复初始状态 （恢复原来数据）
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //要进行实时搜索
    [self doSearch];
    [self.searchDisplayController.searchResultsTableView reloadData];
    return YES;
}

@end
